package com.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.dao.OrderDao;
import com.dao.RoomDao;
import com.form.QueryForm;
import com.model.Room;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 查询空房相关操作类
 * 
 * @author 0912652
 */

public class QueryAction extends ActionSupport implements
		ModelDriven<QueryForm> {

	private QueryForm queryForm = new QueryForm();

	public QueryForm getModel() {
		return queryForm;
	}

	public String queryRoom() {

		RoomDao roomDao = new RoomDao();
		List<Room> rooms = roomDao.findRoomByType(queryForm.getId());
		Map<Room, Integer> keyfreqs = new HashMap<Room, Integer>();

		OrderDao orderDao = new OrderDao();
		for (Room room : rooms) {
			List<QueryForm> queryForms = orderDao.getQueryForms(room.getRid());
			Calendar come = Calendar.getInstance();
			Calendar leave = Calendar.getInstance();
			come.setTime(queryForm.getBegin());
			leave.setTime(queryForm.getEnd());
			for (int i = 0; i < queryForms.size(); i++) {
				QueryForm form = queryForms.get(i);
				Calendar end = Calendar.getInstance();
				end.setTime(form.getEnd());
				int pre = end.compareTo(come);
				if (pre <= 0) {
					QueryForm next = queryForms.get(i + 1);
					Calendar begin = Calendar.getInstance();
					begin.setTime(next.getBegin());
					int after = leave.compareTo(begin);
					if (after <= 0) {
						keyfreqs.put(room, pre + after);
					}
				}

			}
		}

		ArrayList<Entry<Room, Integer>> l = new ArrayList<Entry<Room, Integer>>(
				keyfreqs.entrySet());

		Collections.sort(l, new Comparator<Map.Entry<Room, Integer>>() {
			public int compare(Map.Entry<Room, Integer> o1,
					Map.Entry<Room, Integer> o2) {
				Integer v1 = o1.getValue();
				Integer v2 = o2.getValue();
				return v1.compareTo(v2);
			}
		});

		List<Room> results = Collections.emptyList();
		for (Entry<Room, Integer> e : l) {
			results.add(e.getKey());
		}
		
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		session.setAttribute("rooms", results);

		return "rooms";
	}
	
	public List<Map<Integer, QueryForm>> getOtherRooms(){
		//TODO：前端查询空房如果没有连续空房可点击搜索多间拼凑，递归搜索后，按更换次数最少排列
		
		return null;
		
	}

}
